package sunyu.controller.shiro.realm;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by 孙宇
 */
public class MyRealm extends AuthorizingRealm {

    /**
     * 在调用controller的方法时，如果方法上面有shiro注解，会触发下面的方法
     *
     * @param principalCollection
     *
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //这里应该是从数据库去查询用户的角色，角色的权限等信息
        //建议权限使用  user:create  admin:view   xxx:*  这种权限方式，而不是使用url
        //user:create 就代表，用户功能，创建用户  user:view 就代表显示用户列表  user:query 就代表用户查询功能，以此类推
        String username = principalCollection.getPrimaryPrincipal().toString();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> roleName = new HashSet<String>();
        roleName.add("admin");
        Set<String> permissions = new HashSet<String>();
        permissions.add("index:view");
        info.setRoles(roleName);
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * 调用subject.login(token);的时候，会触发下面的方法
     *
     * @param authenticationToken
     *
     * @return
     *
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        String name = "admin";
        String pwd = "123456";
        pwd = DigestUtils.md5Hex("123456");

        String username = authenticationToken.getPrincipal().toString();
        //T_user user = t_userService.findUserByUsername(username);//这里应该是调用数据库，去查询用户的信息，然后比对密码
        if (name != null) {
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(name, pwd, getName());
            return authenticationInfo;
        } else {
            return null;
        }
    }
}
